# !/usr/bin/python3
# -*- coding: utf-8 -*-

"""
用户信息表服务类
----------------------------------------------------
@Project :   xinhou-openai-framework
@File    :   User.py
@Contact :   sp_hrz@qq.com

@Modify Time      @Author    @Version    @Desciption
------------      -------    --------    -----------
2023/04/16 22:04  peng.shen   v1.0.0     None
"""

from sqlalchemy.orm import Session

from common.entity.User import User
from xinhou_openai_framework.core.orm.service.BaseServiceImpl import BaseServiceImpl
from xinhou_openai_framework.utils.DateUtil import DateUtil
from xinhou_openai_framework.utils.Md5Util import Md5Util


class UserService(BaseServiceImpl[User]):
    """
    用户服务类
    """

    def __init__(self, db: Session):
        super(UserService, self).__init__(db, User)

    def login(self, login_name: str, login_pwd: str) -> dict:
        search = User(**{"login_name": login_name, "login_pwd": Md5Util.md5_string(login_pwd), "del_flag": 1})
        users = self.find_all(search)
        if users and len(users) > 0:
            return {
                "user_id": users[0].id,
                "login_name": users[0].login_name,
                "user_name": users[0].user_name,
                "user_type": users[0].user_type,
                "tenant_id": users[0].tenant_id
            }
        return None

    def register(self, model: User):
        model.login_pwd = Md5Util.md5_string(model.login_pwd)
        model.user_type = 2
        model.update_by = "admin"
        model.updated_at = DateUtil.get_current_datetime()
        model.create_by = "admin"
        model.created_at = DateUtil.get_current_datetime()
        return self.save(model)